<template>
  <div class="min-h-screen bg-gradient-to-br from-blue-50 via-white to-purple-50">
    <div class="container mx-auto px-4 py-8">
      <!-- 页面标题 -->
      <div class="mb-8">
        <h1 class="text-4xl font-bold bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent">
          学习进度
        </h1>
        <p class="text-gray-600 mt-2">跟踪你的学习进度和成就</p>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="flex items-center justify-center py-12">
        <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500"></div>
        <span class="ml-4 text-lg text-gray-600">加载中...</span>
      </div>

      <!-- 错误状态 -->
      <div v-else-if="error" class="bg-red-50 border border-red-200 rounded-lg p-6 mb-8">
        <div class="flex items-center">
          <svg class="w-6 h-6 text-red-500 mr-3" fill="currentColor" viewBox="0 0 20 20">
            <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clip-rule="evenodd"/>
          </svg>
          <div>
            <h3 class="text-lg font-medium text-red-800">加载失败</h3>
            <p class="text-red-600">{{ error }}</p>
          </div>
        </div>
      </div>

      <!-- 主要内容 -->
      <div v-else>

        <!-- 进度概览 -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
          <div class="bg-white rounded-xl shadow-lg hover:shadow-xl transition-all duration-300 p-6 border border-green-100">
            <div class="flex items-center">
              <div class="flex-shrink-0">
                <div class="w-12 h-12 bg-gradient-to-br from-green-400 to-green-600 rounded-xl flex items-center justify-center shadow-lg">
                  <svg class="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                  </svg>
                </div>
              </div>
              <div class="ml-4">
                <p class="text-sm font-medium text-gray-500">已解决题目</p>
                <p class="text-3xl font-bold text-gray-900">{{ progress.solved }}</p>
              </div>
            </div>
          </div>

          <div class="bg-white rounded-xl shadow-lg hover:shadow-xl transition-all duration-300 p-6 border border-blue-100">
            <div class="flex items-center">
              <div class="flex-shrink-0">
                <div class="w-12 h-12 bg-gradient-to-br from-blue-400 to-blue-600 rounded-xl flex items-center justify-center shadow-lg">
                  <svg class="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6"></path>
                  </svg>
                </div>
              </div>
              <div class="ml-4">
                <p class="text-sm font-medium text-gray-500">总积分</p>
                <p class="text-3xl font-bold text-gray-900">{{ progress.score }}</p>
              </div>
            </div>
          </div>

          <div class="bg-white rounded-xl shadow-lg hover:shadow-xl transition-all duration-300 p-6 border border-yellow-100">
            <div class="flex items-center">
              <div class="flex-shrink-0">
                <div class="w-12 h-12 bg-gradient-to-br from-yellow-400 to-orange-500 rounded-xl flex items-center justify-center shadow-lg">
                  <svg class="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"></path>
                  </svg>
                </div>
              </div>
              <div class="ml-4">
                <p class="text-sm font-medium text-gray-500">连续天数</p>
                <p class="text-3xl font-bold text-gray-900">{{ progress.streak }}</p>
              </div>
            </div>
          </div>

          <div class="bg-white rounded-xl shadow-lg hover:shadow-xl transition-all duration-300 p-6 border border-purple-100">
            <div class="flex items-center">
              <div class="flex-shrink-0">
                <div class="w-12 h-12 bg-gradient-to-br from-purple-400 to-purple-600 rounded-xl flex items-center justify-center shadow-lg">
                  <svg class="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                  </svg>
                </div>
              </div>
              <div class="ml-4">
                <p class="text-sm font-medium text-gray-500">学习时长</p>
                <p class="text-3xl font-bold text-gray-900">{{ progress.studyTime }}h</p>
              </div>
            </div>
          </div>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
          <!-- 难度分布 -->
          <div class="bg-white rounded-xl shadow-lg p-6 border border-gray-100">
            <h2 class="text-xl font-bold text-gray-900 mb-6 flex items-center">
              <svg class="w-6 h-6 text-blue-500 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"></path>
              </svg>
              难度分布
            </h2>
            <div class="space-y-6">
              <div>
                <div class="flex justify-between mb-3">
                  <span class="text-sm font-semibold text-gray-700 flex items-center">
                    <div class="w-3 h-3 bg-green-500 rounded-full mr-2"></div>
                    简单
                  </span>
                  <span class="text-sm font-bold text-gray-900">{{ progress.difficultyStats.easy }}/{{ progress.difficultyStats.easyTotal }}</span>
                </div>
                <div class="w-full bg-gray-200 rounded-full h-3 shadow-inner">
                  <div
                    class="bg-gradient-to-r from-green-400 to-green-600 h-3 rounded-full transition-all duration-500"
                    :style="{ width: `${Math.min((progress.difficultyStats.easy / progress.difficultyStats.easyTotal) * 100, 100)}%` }"
                  ></div>
                </div>
              </div>
              
              <div>
                <div class="flex justify-between mb-3">
                  <span class="text-sm font-semibold text-gray-700 flex items-center">
                    <div class="w-3 h-3 bg-yellow-500 rounded-full mr-2"></div>
                    中等
                  </span>
                  <span class="text-sm font-bold text-gray-900">{{ progress.difficultyStats.medium }}/{{ progress.difficultyStats.mediumTotal }}</span>
                </div>
                <div class="w-full bg-gray-200 rounded-full h-3 shadow-inner">
                  <div
                    class="bg-gradient-to-r from-yellow-400 to-orange-500 h-3 rounded-full transition-all duration-500"
                    :style="{ width: `${Math.min((progress.difficultyStats.medium / progress.difficultyStats.mediumTotal) * 100, 100)}%` }"
                  ></div>
                </div>
              </div>
              
              <div>
                <div class="flex justify-between mb-3">
                  <span class="text-sm font-semibold text-gray-700 flex items-center">
                    <div class="w-3 h-3 bg-red-500 rounded-full mr-2"></div>
                    困难
                  </span>
                  <span class="text-sm font-bold text-gray-900">{{ progress.difficultyStats.hard }}/{{ progress.difficultyStats.hardTotal }}</span>
                </div>
                <div class="w-full bg-gray-200 rounded-full h-3 shadow-inner">
                  <div
                    class="bg-gradient-to-r from-red-400 to-red-600 h-3 rounded-full transition-all duration-500"
                    :style="{ width: `${Math.min((progress.difficultyStats.hard / progress.difficultyStats.hardTotal) * 100, 100)}%` }"
                  ></div>
                </div>
              </div>
            </div>
          </div>

          <!-- 学习日历 -->
          <div class="bg-white rounded-xl shadow-lg p-6 border border-gray-100">
            <div class="flex items-center justify-between mb-6">
              <h2 class="text-xl font-bold text-gray-900 flex items-center">
                <svg class="w-6 h-6 text-purple-500 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"></path>
                </svg>
                学习日历
              </h2>
              
              <!-- 视图切换按钮 -->
              <div class="flex bg-gray-100 rounded-lg p-1">
                <button
                  v-for="view in ['week', 'month', 'year']"
                  :key="view"
                  @click="switchCalendarView(view as 'week' | 'month' | 'year')"
                  :class="[
                    'px-3 py-1 text-sm font-medium rounded-md transition-all duration-200',
                    calendarView === view
                      ? 'bg-white text-blue-600 shadow-sm'
                      : 'text-gray-600 hover:text-gray-900'
                  ]"
                >
                  {{ view === 'week' ? '周' : view === 'month' ? '月' : '年' }}
                </button>
              </div>
            </div>
            
            <!-- 日历导航 -->
            <div class="flex items-center justify-between mb-4">
              <button
                @click="navigateCalendar('prev')"
                class="p-2 hover:bg-gray-100 rounded-lg transition-colors"
              >
                <svg class="w-5 h-5 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
                </svg>
              </button>
              
              <h3 class="text-lg font-semibold text-gray-900">{{ calendarTitle }}</h3>
              
              <button
                @click="navigateCalendar('next')"
                class="p-2 hover:bg-gray-100 rounded-lg transition-colors"
              >
                <svg class="w-5 h-5 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
                </svg>
              </button>
            </div>
            
            <!-- 日历内容 -->
            <div v-if="calendarView === 'week'" class="grid grid-cols-7 gap-2 text-center">
              <div class="text-xs font-semibold text-gray-500 py-2">日</div>
              <div class="text-xs font-semibold text-gray-500 py-2">一</div>
              <div class="text-xs font-semibold text-gray-500 py-2">二</div>
              <div class="text-xs font-semibold text-gray-500 py-2">三</div>
              <div class="text-xs font-semibold text-gray-500 py-2">四</div>
              <div class="text-xs font-semibold text-gray-500 py-2">五</div>
              <div class="text-xs font-semibold text-gray-500 py-2">六</div>
              
              <div
                v-for="day in calendarDays.slice(0, 7)"
                :key="day.date"
                :class="[
                  'h-10 w-10 rounded-lg flex items-center justify-center text-sm font-medium transition-all duration-200',
                  day.hasActivity 
                    ? 'bg-gradient-to-br from-green-400 to-green-600 text-white shadow-lg' 
                    : 'text-gray-400 hover:bg-gray-100'
                ]"
              >
                {{ day.day }}
              </div>
            </div>
            
            <div v-else-if="calendarView === 'month'" class="grid grid-cols-7 gap-1 text-center">
              <div class="text-xs font-semibold text-gray-500 py-2">日</div>
              <div class="text-xs font-semibold text-gray-500 py-2">一</div>
              <div class="text-xs font-semibold text-gray-500 py-2">二</div>
              <div class="text-xs font-semibold text-gray-500 py-2">三</div>
              <div class="text-xs font-semibold text-gray-500 py-2">四</div>
              <div class="text-xs font-semibold text-gray-500 py-2">五</div>
              <div class="text-xs font-semibold text-gray-500 py-2">六</div>
              
              <div
                v-for="day in calendarDays"
                :key="day.date"
                :class="[
                  'h-8 w-8 rounded-lg flex items-center justify-center text-xs font-medium transition-all duration-200',
                  day.hasActivity 
                    ? 'bg-gradient-to-br from-green-400 to-green-600 text-white shadow-md' 
                    : 'text-gray-400 hover:bg-gray-100'
                ]"
              >
                {{ day.day }}
              </div>
            </div>
            
            <div v-else-if="calendarView === 'year'" class="grid grid-cols-4 gap-4">
              <div
                v-for="(month, index) in calendarDays"
                :key="month.date"
                :class="[
                  'p-3 rounded-lg text-center transition-all duration-200',
                  month.hasActivity 
                    ? 'bg-gradient-to-br from-green-400 to-green-600 text-white shadow-lg' 
                    : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                ]"
              >
                <div class="text-sm font-semibold">{{ month.day }}月</div>
                <div v-if="month.hasActivity" class="text-xs mt-1">{{ month.count }}题</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 最近成就 -->
        <div class="mt-8">
          <div class="bg-white rounded-xl shadow-lg p-6 border border-gray-100">
            <h2 class="text-xl font-bold text-gray-900 mb-6 flex items-center">
              <svg class="w-6 h-6 text-yellow-500 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4M7.835 4.697a3.42 3.42 0 001.946-.806 3.42 3.42 0 014.438 0 3.42 3.42 0 001.946.806 3.42 3.42 0 013.138 3.138 3.42 3.42 0 00.806 1.946 3.42 3.42 0 010 4.438 3.42 3.42 0 00-.806 1.946 3.42 3.42 0 01-3.138 3.138 3.42 3.42 0 00-1.946.806 3.42 3.42 0 01-4.438 0 3.42 3.42 0 00-1.946-.806 3.42 3.42 0 01-3.138-3.138 3.42 3.42 0 00-.806-1.946 3.42 3.42 0 010-4.438 3.42 3.42 0 00.806-1.946 3.42 3.42 0 013.138-3.138z"></path>
              </svg>
              最近成就
            </h2>
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              <div
                v-for="achievement in achievements"
                :key="achievement.id"
                class="group flex items-center p-4 bg-gradient-to-r from-yellow-50 to-orange-50 border border-yellow-200 rounded-xl hover:shadow-lg transition-all duration-300"
              >
                <div class="flex-shrink-0">
                  <div class="w-12 h-12 bg-gradient-to-br from-yellow-400 to-orange-500 rounded-xl flex items-center justify-center shadow-lg group-hover:scale-110 transition-transform duration-300">
                    <span class="text-white text-xl">{{ achievement.icon || '🏆' }}</span>
                  </div>
                </div>
                <div class="ml-4 flex-1">
                  <div class="font-bold text-gray-900 text-lg">{{ achievement.title }}</div>
                  <div class="text-sm text-gray-600 mt-1">{{ achievement.description }}</div>
                  <div class="text-xs text-gray-500 mt-2 flex items-center">
                    <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                    </svg>
                    {{ formatDate(achievement.earnedAt) }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import { userApi } from '@/api/user'
import { pointsApi } from '@/api/points'

const route = useRoute()

// 响应式数据
const progress = ref({
  solved: 0,
  score: 0,
  streak: 0,
  studyTime: 0,
  difficultyStats: {
    easy: 0,
    easyTotal: 0,
    medium: 0,
    mediumTotal: 0,
    hard: 0,
    hardTotal: 0
  }
})

// 加载状态
const loading = ref(false)
const error = ref('')

// 日历相关
const calendarView = ref<'week' | 'month' | 'year'>('month')
const currentDate = ref(new Date())
const calendarDays = ref<Array<{date: string, day: number, hasActivity: boolean, count: number}>>([])

// 成就数据
const achievements = ref<Array<{
  id: number
  title: string
  description: string
  earnedAt: Date
  icon?: string
}>>([])

// 计算属性
const calendarTitle = computed(() => {
  const date = currentDate.value
  switch (calendarView.value) {
    case 'week':
      const weekStart = new Date(date)
      weekStart.setDate(date.getDate() - date.getDay())
      const weekEnd = new Date(weekStart)
      weekEnd.setDate(weekStart.getDate() + 6)
      return `${weekStart.toLocaleDateString('zh-CN', { month: 'long', day: 'numeric' })} - ${weekEnd.toLocaleDateString('zh-CN', { month: 'long', day: 'numeric' })}`
    case 'month':
      return date.toLocaleDateString('zh-CN', { year: 'numeric', month: 'long' })
    case 'year':
      return date.getFullYear().toString()
    default:
      return ''
  }
})

// 方法
const formatDate = (date: Date) => {
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  })
}

// 生成日历数据
const generateCalendarDays = () => {
  const days: Array<{date: string, day: number, hasActivity: boolean, count: number}> = []
  const date = new Date(currentDate.value)
  
  if (calendarView.value === 'week') {
    // 周视图：显示当前周
    const startOfWeek = new Date(date)
    startOfWeek.setDate(date.getDate() - date.getDay())
    
    for (let i = 0; i < 7; i++) {
      const dayDate = new Date(startOfWeek)
      dayDate.setDate(startOfWeek.getDate() + i)
      const dateStr = dayDate.toISOString().split('T')[0]
      
      days.push({
        date: dateStr,
        day: dayDate.getDate(),
        hasActivity: false, // 将从API获取
        count: 0
      })
    }
  } else if (calendarView.value === 'month') {
    // 月视图：显示当前月
    const year = date.getFullYear()
    const month = date.getMonth()
    const firstDay = new Date(year, month, 1)
    const lastDay = new Date(year, month + 1, 0)
    const startDate = new Date(firstDay)
    startDate.setDate(firstDay.getDate() - firstDay.getDay())
    
    for (let i = 0; i < 42; i++) { // 6周 x 7天
      const dayDate = new Date(startDate)
      dayDate.setDate(startDate.getDate() + i)
      const dateStr = dayDate.toISOString().split('T')[0]
      
      days.push({
        date: dateStr,
        day: dayDate.getDate(),
        hasActivity: false, // 将从API获取
        count: 0
      })
    }
  } else if (calendarView.value === 'year') {
    // 年视图：显示12个月
    const year = date.getFullYear()
    for (let month = 0; month < 12; month++) {
      const monthDate = new Date(year, month, 1)
      const dateStr = monthDate.toISOString().split('T')[0]
      
      days.push({
        date: dateStr,
        day: month + 1,
        hasActivity: false, // 将从API获取
        count: 0
      })
    }
  }
  
  calendarDays.value = days
}

// 切换日历视图
const switchCalendarView = (view: 'week' | 'month' | 'year') => {
  calendarView.value = view
  generateCalendarDays()
  loadCalendarData()
}

// 导航日历
const navigateCalendar = (direction: 'prev' | 'next') => {
  const date = new Date(currentDate.value)
  
  if (calendarView.value === 'week') {
    date.setDate(date.getDate() + (direction === 'next' ? 7 : -7))
  } else if (calendarView.value === 'month') {
    date.setMonth(date.getMonth() + (direction === 'next' ? 1 : -1))
  } else if (calendarView.value === 'year') {
    date.setFullYear(date.getFullYear() + (direction === 'next' ? 1 : -1))
  }
  
  currentDate.value = date
  generateCalendarDays()
  loadCalendarData()
}

// 加载用户统计数据
const loadUserStats = async () => {
  try {
    const [userStatsResponse, pointsResponse] = await Promise.all([
      userApi.getCurrentUserStats(),
      pointsApi.getUserPoints()
    ])
    
    const userStats = userStatsResponse.data
    const pointsData = pointsResponse.data
    
    progress.value = {
      solved: userStats?.solved_count || 0,
      score: pointsData?.total_points || 0,
      streak: userStats?.consecutive_days || 0,
      studyTime: Math.floor((userStats?.total_submissions || 0) * 0.5), // 估算学习时长
      difficultyStats: {
        easy: userStats?.difficulty_stats?.easy_solved || 0,
        easyTotal: 100, // 假设总数
        medium: userStats?.difficulty_stats?.medium_solved || 0,
        mediumTotal: 100,
        hard: userStats?.difficulty_stats?.hard_solved || 0,
        hardTotal: 50
      }
    }
  } catch (error: any) {
    console.error('加载用户统计失败:', error)
    error.value = error?.message || '加载统计数据失败'
  }
}

// 加载日历数据
const loadCalendarData = async () => {
  try {
    const year = currentDate.value.getFullYear()
    const response = await userApi.getUserSolveCalendar(Number(route.params.id) || 0, year)
    const calendarData = response.data
    
    // 更新日历活动状态
    calendarDays.value = calendarDays.value.map(day => {
      const activityCount = calendarData?.[day.date] || 0
      return {
        ...day,
        hasActivity: activityCount > 0,
        count: activityCount
      }
    })
  } catch (error: any) {
    console.error('加载日历数据失败:', error)
  }
}

// 加载成就数据
const loadAchievements = async () => {
  try {
    // 这里应该调用成就API，暂时使用模拟数据
    achievements.value = [
      {
        id: 1,
        title: '初学者',
        description: '解决了第一道题目',
        earnedAt: new Date('2023-01-15'),
        icon: '🎯'
      },
      {
        id: 2,
        title: '坚持不懈',
        description: '连续学习7天',
        earnedAt: new Date('2023-02-01'),
        icon: '🔥'
      },
      {
        id: 3,
        title: '算法新手',
        description: '解决了50道题目',
        earnedAt: new Date('2023-03-10'),
        icon: '💡'
      }
    ]
  } catch (error: any) {
    console.error('加载成就数据失败:', error)
  }
}

// 加载所有数据
const loadAllData = async () => {
  loading.value = true
  error.value = ''
  
  try {
    await Promise.all([
      loadUserStats(),
      loadCalendarData(),
      loadAchievements()
    ])
  } catch (error: any) {
    console.error('加载数据失败:', error)
    error.value = error?.message || '加载数据失败'
  } finally {
    loading.value = false
  }
}

onMounted(async () => {
  generateCalendarDays()
  await loadAllData()
})
</script>
